package com.jia.train.global.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.jia.train.global.auth.BaseUserResponse;
import com.jia.train.global.context.AuthContextHolder;
import com.jia.train.global.utils.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class UserInterceptor implements HandlerInterceptor {

    public static final Logger logger = LoggerFactory.getLogger(UserInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        try {
            if (authorization != null && JwtTokenUtil.validateToken(authorization)) {
                JSONObject authentication = JwtTokenUtil.getAuthentication(authorization);
                BaseUserResponse auth
                        = BeanUtil.copyProperties(authentication, BaseUserResponse.class);
                AuthContextHolder.setContext(auth);
                logger.info("当前用户：{} 访问",auth.getId());
            } else {
                logger.info("无需登录的用户");
            }
            return true;
        } catch (Exception e) {
            logger.error("非法用户:{}", e.getMessage());
            return false;
        }

    }
}
